package com.huajin.codetest.lock.cas;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * https://it007.blog.csdn.net/article/details/103924365
 * 
 * CAS
 * 乐观锁
 * CAS乐观锁对临界区的数据（也就是atomicLong中的volatile long value属性）进行修改，这个属性是热点数据。
 * 并发量高的时候，会出现很多线程都轮询修改value属性的情况，CPU消耗比较高。
 *
 * AtomicInteger
 * AtomicLong CAS 低并发环境下性能好
 * 
 * LongAdder CAS+分段  高并发环境下性能好
 *
 */
public class AtomicTest {
	
	public static void main(String[] args) throws InterruptedException {
        LongAdder longAdder = new LongAdder();
        AtomicLong atomicLong = new AtomicLong();
        ExecutorService threadPool = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 1000000; i++){
            threadPool.execute(() -> {
                longAdder.increment();
                atomicLong.incrementAndGet();
            });
        }
        TimeUnit.SECONDS.sleep(2);//等待线城池执行完成
        System.out.println(longAdder.longValue());
        System.out.println(atomicLong.get());
    }

}
